/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2018 All Rights Reserved.
 */
package com.fulihui.usercore.service;

import com.fulihui.usercore.api.UserExternalService;
import com.fulihui.usercore.core.repository.UserRepository;
import com.fulihui.usercore.dal.dataobj.UserExternalDO;
import com.fulihui.usercore.dal.dataobj.UserExternalDOExample;
import com.fulihui.usercore.dal.mapper.UserExternalDOMapper;
import com.fulihui.usercore.dto.UserDTO;
import com.fulihui.usercore.request.userexternal.UserExternalRequest;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: zhangyingjie
 * @version: v 0.1 2018年01月25日 14:38  zhangyingjie Exp $
 */
@Service(version = "1.0.0")
public class UserExternalServiceImpl implements UserExternalService {
    @Autowired
    private UserExternalDOMapper userExternalDOMapper;
    @Autowired
    private UserRepository userRepository;
    @Override
    public BaseResult saveUserExternal(UserExternalRequest request) {

        //先查询用户外部表 是否已经插入，如果已经插入 就不再插入
        UserExternalDOExample example = new UserExternalDOExample();
        example.createCriteria().andUserIdEqualTo(request.getUserId())
                .andChannelEqualTo(request.getChannel());
        List<UserExternalDO> userExternalDOS = userExternalDOMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(userExternalDOS)){
            //没有值 就插入,先查询用户信息
            UserDTO userDTO = userRepository.queryByPK(request.getUserId());
            if (userDTO != null){
                UserExternalDO userExternalDO = new UserExternalDO();
                BeanUtils.copyProperties(userDTO,userExternalDO);
                userExternalDO.setChannel(request.getChannel());
                userExternalDOMapper.insertSelective(userExternalDO);
            }

        }
        return ResultBuilder.succ();
    }
}
